import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaTools, WeaLocaleProvider, WeaTop, WeaTab, WeaLeftRightLayout, WeaLeftTree, WeaTree, WeaFormItem, WeaSearchGroup, WeaRightMenu, WeaDialog, WeaNewScroll, WeaAlertPage } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { Button, Form } from 'antd';
import HighSeasSettingForm from './HighSeasSettingForm';
import HighSeasLogDialog from '../dialog/HighSeasLogDialog';

@inject('highSeasSettingListStore', 'highSeasSettingFormStore')
@observer
class HighSeasSettingList extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { highSeasSettingListStore, highSeasSettingFormStore } = this.props;
    if (window.weaCrmEngine) {
      highSeasSettingListStore.initDatas(highSeasSettingFormStore);
    } else {
      eventRegister.loadModule('b_crm', () => {
        highSeasSettingListStore.initDatas(highSeasSettingFormStore);
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { highSeasSettingListStore } = nextProps;
      highSeasSettingListStore.initDatas();
    }
  }


  render() {
    const { highSeasSettingListStore, highSeasSettingFormStore } = this.props;
    const { tableStore, loading, showSearchAd, searchConditionForm, showLeft, rightMenus, hrmList, dialogInfo, hasSeasRight, verified, CrmLogStore, logDialogVisible, searchBaseParams } = highSeasSettingListStore;
    const { tabKey, right } = highSeasSettingFormStore;
    const dialogButtons = [];
    right && tabKey == 0 && dialogButtons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oa2g6i@save`} type="primary" disabled={loading || dialogInfo.disabled} onClick={() => highSeasSettingListStore.controlOperateDialog('save', highSeasSettingFormStore.initForm, toJS(highSeasSettingFormStore.formInfo))} >{getLabel(86, '保存')}</Button>);
    dialogButtons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@phmsx3@close`} onClick={() => highSeasSettingListStore.controlOperateDialog('toback', '')}>{getLabel(309, '关闭')}</Button>);
    if (verified && !hasSeasRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@x1r47z`} >
        <div style={{ color: '#000' }}>
          {getLabel(2012, '对不起，您暂时没有权限！')}
        </div>
      </WeaAlertPage>
      );
    }


    if (verified && hasSeasRight) {
      return (
        <div>
          <WeaRightMenu
            ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@6tu25c`}
            datas={this.getRightMenus()}
            onClick={this.onRightMenusClick.bind(this)}
            collectParams={{
              favname: getLabel(386603, '公海管理'),
              favouritetype: 4,
              importantlevel: 1,
              objid: -1,
            }}
          >
            <WeaTop
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@7z1fkv`}
              title={getLabel(386603, '公海管理')}
              icon={<i className="icon-coms-crm" />}
              iconBgcolor="#96358a"
              buttons={this.getButtons(this.props.ecId || '')}
              loading={loading}
              buttonSpace={10}
              dropMenuDatas={this.getRightMenus()}
            >
              <WeaLeftRightLayout
                ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@1y49wd`}
                leftWidth={240}
                leftCom={
                  <WeaLeftTree
                    ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@umfpuz`}
                    searchLabel={getLabel(17494, '所有下属')}
                    defaultExpandLevel="2"
                    datas={toJS(hrmList)}
                    onSelect={(ids, nodeids, nodes, event) => highSeasSettingListStore.onLeftChange(ids)}
                  />
                }
                onCollapse={showLeft => highSeasSettingListStore.isShowLeft(showLeft)}
                showLeft={showLeft}
              >
                <WeaTab
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@qulvpj`}
                  searchType={['base', 'advanced']}
                  keyParam="viewcondition" // 主键
                  searchsBaseValue={(searchBaseParams && searchBaseParams.name) || ''}
                  onSearchChange={v => highSeasSettingListStore.setSearchKey(v)}
                  showSearchAd={showSearchAd}
                  buttonsAd={this.getAdButtons(highSeasSettingListStore, this.props.ecId || '')}
                  setShowSearchAd={bool => highSeasSettingListStore.setShowSearchAd(bool)}
                  hideSearchAd={() => highSeasSettingListStore.setShowSearchAd(false)}
                  searchsAd={<Form ecId={`${this && this.props && this.props.ecId || ''}_Form@z3jrqr`} horizontal>{this.getSearchConditionForm(highSeasSettingListStore)}</Form>}
                  onSearch={highSeasSettingListStore.doSearch}
                />
                <WeaTable
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@m8lssi`}
                  comsWeaTableStore={tableStore}
                  hasOrder
                  needScroll
                  getColumns={columns => this.getColumns(columns)}
                  onOperatesClick={(record, index, operate, flag) => this.onOperatesClick(record, index, operate, flag)}
                />

              </WeaLeftRightLayout>
            </WeaTop>
          </WeaRightMenu>
          {(dialogInfo.visible && <WeaDialog
            ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@sxnn6l`}
            buttons={dialogButtons}
            title={dialogInfo.title}
            iconBgcolor="#96358a"
            icon="icon-coms-crm"
            visible={dialogInfo.visible}
            onCancel={() => highSeasSettingListStore.controlOperateDialog('toback')}
            style={{ width: 1100, height: 600 }}
            hasScroll
          >
            <HighSeasSettingForm ecId={`${this && this.props && this.props.ecId || ''}_HighSeasSettingForm@lyo7u3`} highSeasSettingListStore={highSeasSettingListStore} />
          </WeaDialog>)}
          {window.weaCrmEngine && window.weaCrmEngine.com && window.weaCrmEngine.com.CrmLog && <window.weaCrmEngine.com.CrmLog ecId={`${this && this.props && this.props.ecId || ''}_undefined@igf5v2`} logStore={CrmLogStore} />}
          <HighSeasLogDialog ecId={`${this && this.props && this.props.ecId || ''}_HighSeasLogDialog@8kc68k`} contentStore={highSeasSettingListStore} logType={'1,2,3,4'} />
        </div>
      );
    }
    return <div />;
  }

  getAdButtons(store, ecId) {
    const { doSearch, setShowSearchAd, clearAdFields } = store;
    return [
      (<Button ecId={`${ecId}_Button@fr1dsx@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${ecId}_Button@7n7h2t@reset`} type="ghost" onClick={() => { clearAdFields(); }}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${ecId}_Button@lvro8t@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
    ];
  }

  getSearchConditionForm(store) {
    const { searchConditionComponents, searchConditionForm } = store;
    const groups = [];
    if (searchConditionComponents) {
      const { isFormInit } = searchConditionForm;
      const formParams = searchConditionForm.getFormParams();
      isFormInit && toJS(searchConditionComponents).map((c, i) => {
        const items = [];
        c.items.map((fields, index) => {
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6xzolw@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8rznry@${fields.domkey[0]}`} fieldConfig={fields} form={searchConditionForm} formParams={formParams} onChange={store.searchConditionFieldChange} onEnterSearch={this.onEnterSearch} />
            </WeaFormItem>),
            col: 2,
          });
        });
        groups.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wba84r@${i}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
    }
    return groups;
  }

  getRightMenus() {
    const { highSeasSettingListStore } = this.props;
    const { rightMenus, tableStore } = highSeasSettingListStore;
    const { selectedRowKeys } = tableStore;
    const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
    const btnArr = [];
    rightMenus && rightMenus.map((m) => {
      btnArr.push({
        icon: <i className={m.menuIcon} />,
        content: m.menuName,
        disabled: isDisabled && m.isControl == '1',
      });
    });
    return btnArr;
  }

  getHrmTree() {
    const { highSeasSettingListStore } = this.props;
    const { hrmList } = highSeasSettingListStore;
  }

  onRightMenusClick(key) {
    const { highSeasSettingListStore, highSeasSettingFormStore } = this.props;
    const { rightMenus, tableStore } = highSeasSettingListStore;
    const { selectedRowKeys } = tableStore;
    rightMenus && rightMenus.length > 0 && rightMenus.map((m, i) => {
      if (Number(key) == i) {
        const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
        if (m.type == 'BTN_CREATE') {
          highSeasSettingListStore.controlOperateDialog('add', '');
        } else if (m.type == 'BTN_DELETE') {
          highSeasSettingListStore.controlOperateDialog('delete', '', toJS(selectedRowKeys));
        } else if (m.type == 'BTN_EDITLOG') {
          highSeasSettingListStore.controlOperateDialog('showlog', '', {});
        } else if (m.type == 'BTN_MONITERLOG') {
          highSeasSettingListStore.controlOperateDialog('showMonitorLog', '', {});
        }
      }
    });
  }

  getButtons(ecId) {
    const { highSeasSettingListStore, highSeasSettingFormStore } = this.props;
    const { tableStore, rightMenus } = highSeasSettingListStore;
    const { selectedRowKeys } = tableStore;
    const btnArr = [];
    const that = this;
    const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
    rightMenus && rightMenus.length > 0 && rightMenus.map((m) => {
      m.isTop == '1' && btnArr.length < 4 && btnArr.push(
        <Button
          ecId={`${ecId}_Button@gaobxb@${m.type}`}
          type="primary"
          disabled={isDisabled && m.isControl == '1'}
          onClick={() => {
            const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
            if (m.type == 'BTN_CREATE') {
              highSeasSettingListStore.controlOperateDialog('add', '');
            } else if (m.type == 'BTN_DELETE') {
              highSeasSettingListStore.controlOperateDialog('delete', '', toJS(selectedRowKeys));
            }
          }}
        >
          {m.menuName}
        </Button>,
      );
    });
    return btnArr;
  }

    getColumns = (columns) => {
      const that = this;
      const { highSeasSettingListStore } = this.props;
      columns.forEach((c) => {
        if (c.dataIndex == 'name') {
          c.render = function (text, record) {
            return (<div onClick={(bool) => { highSeasSettingListStore.controlOperateDialog('edit', '', { id: record.randomFieldId }); }}>
              <a>{text}</a>
            </div>);
          };
        } else if (c.dataIndex == 'status') {
          c.render = function (text, record) {
            return (<div style={{ color: `${record.status == '1' ? 'green' : 'red'}` }}>
              {record.statusspan}
            </div>);
          };
        } else if (c.dataIndex == 'customerNum') {
          c.render = function (text, record) {
            return (<div style={{ color: `${!record.customerNumspan ? '' : 'red'}` }}>
              {record.customerNumspan || 0}
            </div>);
          };
        } else {
          c.render = function (text, record) {
            const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
            return <span dangerouslySetInnerHTML={{ __html: valueSpan }} />;
          };
        }
      });
      return columns;
    }


    onOperatesClick(record, index, operate, flag) {
      const { highSeasSettingListStore } = this.props;
      const { onOperates } = highSeasSettingListStore;
      if (onOperates && operate.otherpara && operate.otherpara == 'doSynchroniz') {
        highSeasSettingListStore.doSynchroniz(record.randomFieldId);
      }
      if (operate.otherpara && operate.otherpara == 'doShowLog') {
        highSeasSettingListStore.controlOperateDialog('showlog', '', { seasId: record.randomFieldId });
      }
      if (operate.otherpara && operate.otherpara == 'doShowMonitorLog') {
        highSeasSettingListStore.controlOperateDialog('showMonitorLog', '', { seasId: record.randomFieldId });
      }
    }

    onEnterSearch=() => {
      const { highSeasSettingListStore } = this.props;
      highSeasSettingListStore.doSearch();
    }
}
export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@9s28v1`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(HighSeasSettingList);
